import java.awt.Image;
import java.awt.Rectangle;
import java.io.IOException;
import javax.imageio.ImageIO;


public class Egg {

	public double y;
	public double x;

	private double speed = 10;
	private Image image;
	private int imageWidth = 20;
	private int imageHeight = 20;
	private int type;

	private boolean isExploding = false;
	private double	explosionBeginTime = 0;
	private Image[] imageArrayExplosion = new Image[3];
	private int		imgExplosion = 0;
	private boolean hasExplosed = false;

	public Egg(double posX, double posY, int type){

		this.x = posX;
		this.y = posY;
		this.type = type;
		this.loadExplosionImg();
		this.loadEggImg();

	}

	private void loadExplosionImg(){
		try {
			for(int i=0; i<this.imageArrayExplosion.length; ++i){
				this.imageArrayExplosion[i] = ImageIO.read((getClass().getResource("Ressources/explo_20_px_"+i+".png")));
			}
		} 
		catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void loadEggImg(){
		try {
			this.image = ImageIO.read((getClass().getResource("Ressources/egg.png")));
		} 
		catch (IOException e) { e.printStackTrace();}	
	}

	private void updateExplosion(){
		double time_passed;

		time_passed = (System.currentTimeMillis() - this.explosionBeginTime);
		if(time_passed < 100) 
			this.imgExplosion = 0;
		else if(time_passed < 200) 
			this.imgExplosion = 1;
		else if(time_passed < 300) 
			this.imgExplosion = 2;
		else{
			this.hasExplosed = true;
		}
	}

	public void nextStep(){
		if(!this.isExploding){
			this.y += speed;
		}
		else if(!this.hasExplosed){
			this.updateExplosion();
		}
	}

	public void explose(){
		if(!this.isExploding){
			this.explosionBeginTime = System.currentTimeMillis();
			this.isExploding = true;
			this.hasExplosed = false;
		}
	}

	public boolean isExploding(){
		return this.isExploding;
	}

	/**
	 * @param map
	 * @return typeSol si collision.
	 */
	public int updatePhysics(Map map) {
		Rectangle eggRec = new Rectangle((int)this.x, (int)this.y, this.imageWidth, this.imageHeight);
		int typeSol = 0;
		if(this.isExploding){
			return 0;
		}
		for(int i=0; i< GameControler.NUMBER_OF_TILES_HEIGHT; ++i) {
			for(int y=0; y< GameControler.NUMBER_OF_TILES_WIDTH; ++y) {
				if(map.getValue(y, i) <= 4 && map.getValue(y, i) >= 1) {
					Rectangle mapBlockRec = new Rectangle(y*GameControler.TILES_SIZE,i*GameControler.TILES_SIZE,GameControler.TILES_SIZE,GameControler.TILES_SIZE);
					if(eggRec.intersects(mapBlockRec)){
						typeSol = map.getValue(y, i);
						map.hitBlock(y, i, this.type);
					}
				}
			}	
		}
		return typeSol;
	}

	public Image getImage(){
		if(!this.isExploding){
			return this.image;
		}
		else if(!this.hasExplosed){
			return this.imageArrayExplosion[this.imgExplosion];
		}
		else {return null;}
	}

	public int getType() { return this.type; }
	public int getImageWidth() { return this.imageWidth; }
	public int getImageHeight() { return this.imageHeight;}
	public boolean hasExplode() { return this.hasExplosed;}	
}
